183C - Cyclic Coloring - CodeForces Solution


dfs and similar *2200

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=200010;
int n,m,ans,tot,d[N],e[N],nt[N],hd[N],val[N];
void build(int x,int y,int z){
	tot++;
	e[tot]=y;val[tot]=z;
	nt[tot]=hd[x];hd[x]=tot;
}
int gcd(int x,int y){
	if(!y)return x;
	return gcd(y,x%y);
}
void dfs(int x,int now){
	int i;
	if(d[x]){
		ans=gcd(ans,now-d[x]);
		return;
	}
	d[x]=now;
	for(i=hd[x];i;i=nt[i]) dfs(e[i],now+val[i]);
}
int main(){
	int i,x,y;
	scanf("%d%d",&n,&m);
	for(i=1;i<=m;i++){
		scanf("%d%d",&x,&y);
		build(x,y,1);build(y,x,-1);
	}
	for(i=1;i<=n;i++) if(!d[i]) dfs(i,n+n);
	printf("%d",ans?abs(ans):n);
}


Comments

Submit
0 Comments
More Questions

1391B - Fix You
988B - Substrings Sort
312A - Whose sentence is it
513A - Game
1711E - XOR Triangle
688A - Opponents
20C - Dijkstra
1627D - Not Adding
893B - Beautiful Divisors
864B - Polycarp and Letters
1088A - Ehab and another construction problem
1177B - Digits Sequence (Hard Edition)
1155B - Game with Telephone Numbers
1284A - New Year and Naming
863B - Kayaking
1395B - Boboniu Plays Chess
1475D - Cleaning the Phone
617B - Chocolate
1051B - Relatively Prime Pairs
95B - Lucky Numbers
1692D - The Clock
1553D - Backspace
1670D - Very Suspicious
1141B - Maximal Continuous Rest
1341A - Nastya and Rice
1133A - Middle of the Contest
385A - Bear and Raspberry
1311B - WeirdSort
1713F - Lost Array
236B - Easy Number Challenge